package com.zp.manager.websocket;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.zp.constants.SpaceUserPermissionConstant;
import com.zp.domain.entity.Picture;
import com.zp.domain.entity.Space;
import com.zp.domain.entity.User;
import com.zp.enums.SpaceTypeEnum;
import com.zp.manager.auth.SpaceUserAuthManager;
import com.zp.service.PictureService;
import com.zp.service.SpaceService;
import com.zp.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * WebSocket 握手拦截器
 */
@Component
@Slf4j
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {
    @Resource
    private UserService userService;
    @Resource
    private PictureService pictureService;
    @Resource
    private SpaceService spaceService;
    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    /**
     * 握手之前被调用, 处理前置逻辑(如身份验证)
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        // 转换为 HttpServletRequest
        if (request instanceof ServletServerHttpRequest) {
            HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
            // 缺少图片参数, 拒绝握手
            String pictureId = servletRequest.getParameter("pictureId");
            if (StrUtil.isBlank(pictureId)) {
                log.error("缺少图片参数, 拒绝握手");
                return false;
            }
            // 未登录, 拒绝握手
            User loginUser = userService.getLoginUser(servletRequest);
            if (ObjUtil.isNull(loginUser)) {
                log.error("用户未登录, 拒绝握手");
                return false;
            }
            // 图片不存在, 拒绝握手
            Picture picture = pictureService.getById(pictureId);
            if (ObjUtil.isNull(picture)) {
                log.error("图片不存在, 拒绝握手");
                return false;
            }
            // 空间不存在, 拒绝握手
            Long spaceId = picture.getSpaceId();
            Space space = null;
            if (spaceId != null) {
                space = spaceService.getById(spaceId);
                if (ObjUtil.isNull(space)) {
                    log.error("空间不存在, 拒绝握手");
                    return false;
                }
                // 非团队空间, 拒绝握手
                if (ObjUtil.notEqual(space.getSpaceType(), SpaceTypeEnum.TEAM.getValue())) {
                    log.error("非团队空间, 拒绝握手");
                    return false;
                }
            }
            // 没有图片编辑权限, 拒绝握手
            List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
            if (!permissionList.contains(SpaceUserPermissionConstant.PICTURE_EDIT)) {
                log.error("没有图片编辑权限, 拒绝握手");
                return false;
            }
            // 给 WebSocketSession 添加属性
            attributes.put("user", loginUser);
            attributes.put("userId", loginUser.getId());
            attributes.put("pictureId", Long.valueOf(pictureId));
        }
        return true;
    }

    /**
     * 握手之后被调用, 处理清理工作
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        log.info("afterHandshake, 空实现");
    }
}
